package mlp.game.fluttermat;

import java.math.BigDecimal;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class FluttermatActivity extends Activity {
	static final String TAG = "Fluttermat";
	Handler h = new Handler();
	Vibrator v;
	
	int hits = 0;
	int gameTime = 10 * 1000;
	long startTime = 0;
	
	int b_w = 0;
	int b_h = 0;
	
	String shareText = "Dafuq?";
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        
    	((RelativeLayout)findViewById(R.id.stage_game)).setVisibility(View.GONE); 
    	((RelativeLayout)findViewById(R.id.stage_end)).setVisibility(View.GONE); 
    	((RelativeLayout)findViewById(R.id.stage_intro)).setVisibility(View.VISIBLE); 
        
    	SharedPreferences preferences = getSharedPreferences(TAG, Context.MODE_PRIVATE);
    	if(preferences.getInt("hits", 0) > 0){
    		hits = preferences.getInt("hits", 0);
    		onGameOver();
    	}
    	
        Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/celestiaredux.ttf");
        Tools.setTypeFace(this, tf, R.id.button1, R.id.textView1, R.id.textView2, R.id.txt_hits, R.id.txt_time, R.id.button2, R.id.txt_result);
                
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inScaled = true;
        Bitmap b =  BitmapFactory.decodeResource(getResources(), R.drawable.mat, opts);       
       
        final Bitmap mutableBitmap = b.copy(Bitmap.Config.ARGB_8888, true);
        b_w = mutableBitmap.getWidth();
        b_h = mutableBitmap.getHeight();
        
        final Canvas c = new Canvas(mutableBitmap);
        ((ImageView)findViewById(R.id.img_mat)).setImageBitmap(mutableBitmap);
		((TextView)findViewById(R.id.txt_hits)).setText("Hits: " + hits);
               
        final Bitmap hit = BitmapFactory.decodeResource(getResources(), R.drawable.print);
        
        final DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        
        ((ImageView)findViewById(R.id.img_mat)).setOnTouchListener(new OnTouchListener() {			
			@Override
			public boolean onTouch(View view, MotionEvent event) {
				
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					hits += 1;
					float x = b_w * (event.getX() / dm.widthPixels);
					float y = b_h * (event.getY() / dm.heightPixels);
					((TextView)findViewById(R.id.txt_hits)).setText("Hits: " + hits);
					((ImageView)findViewById(R.id.img_mat)).invalidate();
					v.vibrate(50);

					Matrix matrix = c.getMatrix();
					float angle = (float) (Math.random() * 360);
					c.rotate(angle, x + hit.getWidth() / 2, y + hit.getHeight() / 2);
					c.drawBitmap(hit, x - hit.getWidth() / 2, y - hit.getHeight() / 2, null);
					c.setMatrix(matrix);
				}
				return true;
			}
		});
    }
    
    public void onGameOver(){
    	((RelativeLayout)findViewById(R.id.stage_game)).setVisibility(View.GONE);    
    	((RelativeLayout)findViewById(R.id.stage_end)).setVisibility(View.VISIBLE);  
    	if(hits > 0){
    		((ImageView)findViewById(R.id.image_result)).setImageResource(R.drawable.cry);
    		((TextView)findViewById(R.id.txt_result)).setText(getString(R.string.end_cry, hits));
    		shareText = getString(R.string.end_cry_share, hits);
    	}else{
    		((ImageView)findViewById(R.id.image_result)).setImageResource(R.drawable.happy);
    		((TextView)findViewById(R.id.txt_result)).setText(getString(R.string.end_happy));
    		shareText = getString(R.string.end_happy_share);
    	}
    	SharedPreferences preferences = getSharedPreferences(TAG, Context.MODE_PRIVATE);
    	Editor editor = preferences.edit();
    	editor.putInt("hits", hits);
    	editor.commit();
    }
    
    public void onShareClick(View v){
    	Intent intent = new Intent(Intent.ACTION_SEND);
    	intent.setType("text/plain");
    	intent.putExtra(Intent.EXTRA_TEXT, shareText);
    	startActivityForResult(Intent.createChooser(intent, "Share with"), 20);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if(requestCode == 20){
    		SharedPreferences preferences = getSharedPreferences(TAG, Context.MODE_PRIVATE);
        	Editor editor = preferences.edit();
        	editor.putInt("hits", 0);
        	editor.commit();
        	Intent i = getIntent();
        	finish();
        	startActivity(i);
    	}
    	super.onActivityResult(requestCode, resultCode, data);
    }
    
    public void onStartClick(View v){
    	((RelativeLayout)findViewById(R.id.stage_intro)).setVisibility(View.GONE);
    	((RelativeLayout)findViewById(R.id.stage_game)).setVisibility(View.VISIBLE);
    	startTime = SystemClock.elapsedRealtime();    	
    	h.postDelayed(timeTick, 100);
    }
    
    public Runnable timeTick = new Runnable() {		
		@Override
		public void run() {
			runOnUiThread(new Runnable() {						
				@Override
				public void run() {
					long now = SystemClock.elapsedRealtime();
					int timeLeft = (int) (gameTime - (now - startTime));						
					((TextView)findViewById(R.id.txt_time)).setText("Time left: " + round((timeLeft / 1000f), 2, BigDecimal.ROUND_HALF_UP) + "s");
					if(SystemClock.elapsedRealtime() - startTime > gameTime){
						onGameOver();
					} else {
						h.postDelayed(timeTick, 100);
					}
				}
			});		
	    	
		}
	};
      
    public static double round(double unrounded, int precision, int roundingMode) {
        BigDecimal bd = new BigDecimal(unrounded);
        BigDecimal rounded = bd.setScale(precision, roundingMode);
        return rounded.doubleValue();
    }
}